import { create } from 'zustand'
import { immer } from 'zustand/middleware/immer'
import { persist, createJSONStorage } from 'zustand/middleware'

// persist 是 zustand 提供的一个用于持久化状态的工具，它可以帮助我们更好地管理状态，默认是存储在 localStorage 中，可以指定存储方式
interface StateData {
    count: number,
    increment: () => void,
    decrement: () => void
    testObj: {
        name: string,
        age: number
    },
    updateName: (name: string) => void
    updateAge: (age: number) => void
}

// 
export const usePersistore = create<StateData>()(immer(persist((set) => ({
    count: 0,
    increment: () => set((state) => {
        state.count++
    }),
    decrement: () => set((state) => {
        state.count--
    }),
    testObj: {
        name: '测试二级对象',
        age: 18
    },
    updateName: (name: string) => set((state) => {
        state.testObj.name = name
    }),
    updateAge: (age: number) => set((state) => {
        state.testObj.age = age
    })
}),
    {
        name: 'userPersist', // 仓库名称(唯一)
        storage: createJSONStorage(() => localStorage), // 存储方式 可选 localStorage sessionStorage IndexedDB 默认localStorage
        partialize: (state) => ({
            count: state.count,
            testObj: state.testObj,
        }), // 部分状态持久化，返回对象就行，可以用if等写逻辑
        onRehydrateStorage: (state) => {
            // 当状态从存储中恢复时调用
            console.log('Rehydrated state:', state);
        }
    }

)))
